//
//  HMUserAccountViewModel.swift
//  WeiBo
//
//  Created by Feng on 2017/6/7.
//  Copyright © 2017年 feng. All rights reserved.
//

import UIKit

class HMUserAccountViewModel: NSObject {

    //单例
    static let sharedUserAccount = HMUserAccountViewModel()
    
    //模型数据
    var userAccount: HMUserAccount?
    
    //重写构造函数,目的是一加载这个类,就读取数据
    override init() {
        
        super.init()
        
        self.userAccount = HMUserAccount.loadUserInfoData()
    }
    
    //获取Access_Token(计算属性)
    var accessToken: String?
    {
        //判断是否有值
        guard let token = userAccount?.access_token else{
            return nil
        }
        
        //判断是否过期
        if userAccount?.expires_Date?.compare(Date()) == .orderedDescending
        {
            //表示过期日期大于现在的日期
            return token
        }
        else
        {
            return nil
        }
    }
    
    //判断登录状态,是由Access_Token决定(计算属性)
    var isLogin: Bool
    {
        //这句代码的执行要用到上面的var accessToken: String? 代码
        return accessToken != nil
    }
    
    //MARK: --加载Access_Token
    func requestAccessToken(code: String, callBack: @escaping (Bool)->())
    {
        NetworkTools.shareTools.requestAccessToken(code: code, callBack: { (response, error) in
            
            if error != nil
            {
                print("Access_Token加载出错 = \(error!)")
                callBack(false)
                return
            }
            else
            {
                if let res = response
                {
//                    print("res = \(res)")
                    //创建账号模型
                    let account = HMUserAccount(dict: res as! [String : Any])
                    self.requestUserAccount(userAccount: account, callBack: callBack)
                }
            }
        })
    }
    
    //MARK: --加载用户信息
    func requestUserAccount(userAccount: HMUserAccount, callBack: @escaping (Bool)->())
    {
        NetworkTools.shareTools.requestUserInfo(access_token: userAccount.access_token!, uid: userAccount.uid) { (response, error) in
            
            if error != nil
            {
                print("用户信息加载出错 = \(error!)")
                //登录失败回调
                callBack(false)
                return
            }
            else
            {
                if let userResult = response
                {
                    //将name,avatar_large 数据增入用户模型
                    let userDict: [String: Any] = userResult as! [String : Any]
                    userAccount.name = userDict["name"] as? String
                    userAccount.avatar_large = userDict["avatar_large"] as? String
                    
                    //存储当前数据
                    self.userAccount = userAccount
                    //存入沙盒
                    self.userAccount?.saveUserInfoData()
                    //登录成功回到
                    callBack(true)
                }
            }
        }
    }

}
